﻿using AutoMapper;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Drawing.Printing;
using Zhao.Arena.Utility.InitDatabaseExt;
using Zhao.Common.Helper;
using Zhao.IServer.User;
using Zhao.Models.DTO;
using Zhao.Models.Entity;
using Zhao.Service.User;

namespace Zhao.Arena.Controllers.User
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class RoleController : ControllerBase
    {
        private readonly IMapper _mapper;
        private IRolesServer _rolesServer;
        private IAdminServer _adminServer;
        public RoleController(IRolesServer rolesServer,IMapper mapper, IAdminServer adminServer)
        {
            this._rolesServer = rolesServer;
            this._mapper = mapper;
            this._adminServer = adminServer;
        }


        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="searchaString"></param>
        /// <returns></returns>
        [HttpGet()]
        [Route("{pageIndex:int}/{pageSize:int}")]
        [Route("{pageIndex:int}/{pageSize:int}/{searchaString}")]
        [Function("角色详情", null, "role", "../views/Home/role/info/index.vue")]
        public async Task<JsonResult> GetRolePage(int pageIndex = 1, int pageSize = 10, string searchaString = " ")
        {
            Expressionable<Roles> expressionable = new Expressionable<Roles>();

            var result = new ApiResult<PageModel<RolesDto>>() { Success = false, Message = "操作失败" };

            expressionable.AndIF(!searchaString.IsNullOrWhiteSpace(), u => u.Description.Contains(searchaString) || u.RoleName.Contains(searchaString));

            var data = await _rolesServer.QueryPageAsync(expressionable.ToExpression(), null, pageIndex, pageSize);

            result.Data = _mapper.Map<PageModel<RolesDto>>(data);

            if (result.Data != null)
            {
                result.Success = true;
                result.Message = "操作成功";
            }

            return new JsonResult(result);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="searchaString"></param>
        /// <returns></returns>
        [HttpGet()]
        [Route("{searchaString}")]
        public async Task<JsonResult> GetRole( string searchaString = " ")
        {
            Expressionable<Roles> expressionable = new Expressionable<Roles>();

            var result = new ApiResult<bool>() { Success = false, Message = "操作失败" };

            expressionable.AndIF(!searchaString.IsNullOrWhiteSpace(), u =>  u.RoleName.Equals(searchaString));

            result.Data =await  _rolesServer.QueryCountAsync(expressionable.ToExpression())>0;

            if (result.Data)
            {
                result.Success = true;
                result.Message = "已存在";
            }

            return new JsonResult(result);
        }


        /// <summary>
        /// 根据ID获取角色详情
        /// </summary>
        [HttpGet("{id:int}")]
        public async Task<JsonResult> GetRoleById(int id)
        {
            var result = new ApiResult<RolesDto>() { Success = false, Message = "操作失败" };

            if (id == 0)
            {
                return new JsonResult(result);
            }

            var role = await _rolesServer.QueryAsync(x=>x.RoleID==id);
            if (role == null)
            {
                result.Message = "角色不存在";
                return new JsonResult(result);
            }

            result.Data = _mapper.Map<RolesDto>(role);
            result.Success = true;
            result.Message = "操作成功";

            return new JsonResult(result);
        }

        /// <summary>
        /// 创建新角色
        /// </summary>
        [HttpPost]
        public async Task<JsonResult> CreateRole([FromBody] RolesDto roleDto)
        {
            var result = new ApiResult<bool> { Success = false, Message = "操作失败" };

            // 检查角色名称是否已存在
            if (await _rolesServer.QueryAsync(r => r.RoleName == roleDto.roleName) != null)
            {
                result.Message = "角色名称已存在";
                return new JsonResult(result);
            }

            var role = _mapper.Map<Roles>(roleDto);
            role.CreateTime = DateTime.Now;
            role.IsDeleted = false;

            var rows = await _rolesServer.AddAsync(role);

            result.Success = rows > 0;
            result.Message = result.Success ? "创建成功" : "创建失败";
            result.Data = result.Success;

            return new JsonResult(result);
        }

        /// <summary>
        /// 更新角色信息
        /// </summary>
        [HttpPut]
        public async Task<JsonResult> UpdateRole([FromBody] RolesDto roleDto)
        {
            var result = new ApiResult<bool> { Success = false, Message = "操作失败" };

            var existingRole = await _rolesServer.QueryAsync(roleDto.Id);
            if (existingRole == null)
            {
                result.Message = "角色不存在";
                return new JsonResult(result);
            }

            // 检查角色名称是否被其他角色使用
            if (await _rolesServer.QueryAsync(r => r.RoleID != roleDto.Id && r.RoleName == roleDto.roleName) != null)
            {
                result.Message = "角色名称已被其他角色使用";
                return new JsonResult(result);
            }

            _mapper.Map(roleDto, existingRole);
            var success = await _rolesServer.UpdateAsync(existingRole);

            result.Success = success;
            result.Message = success ? "更新成功" : "更新失败";
            result.Data = success;

            return new JsonResult(result);
        }

        /// <summary>
        /// 删除角色
        /// 1、验证--如果角色被使用，应该不能删除
        /// 2、假删除----对于一些有用的数据--做假删除
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<JsonResult> DeleteRole(int id)
        {
            var result = new ApiResult<bool> { Success = false, Message = "操作失败" };

            //验证角色是否有管理员使用(只要有一个管理员使用就不支持删除当前角色)
            var admins= await _adminServer.QueryAsync(x=>x.Role==id);

            if (admins!=null)
            {
                result.Message = "当前角色正在被使用";
                return new JsonResult(result);
            }

            var role = await _rolesServer.QueryAsync(id);

            if (role==null)
            {
                result.Message = "未查询到数据";
                return new JsonResult(result);
            }

            //做假删除
            var success = await _rolesServer.UpdateAsync(role);

            result.Success = success;
            result.Message = success ? "删除成功" : "删除失败";
            result.Data = success;

            return new JsonResult(result);
        }

        /// <summary>
        /// 启用/禁用角色
        /// </summary>
        [HttpPut("status/{id:int}/{status:int}")]
        public async Task<JsonResult> ChangeRoleStatus(int id, int status)
        {
            var result = new ApiResult<bool> { Success = false, Message = "操作失败" };

            if (status != 0 && status != 1)
            {
                result.Message = "状态值无效（0-禁用，1-启用）";
                return new JsonResult(result);
            }

            var role = await _rolesServer.QueryAsync(id);
            if (role == null)
            {
                result.Message = "角色不存在";
                return new JsonResult(result);
            }

            role.Status = status;
            var success = await _rolesServer.UpdateAsync(role);

            result.Success = success;
            result.Message = success ? "状态更新成功" : "状态更新失败";
            result.Data = success;

            return new JsonResult(result);
        }


        /// <summary>
        /// 获取角色所有数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetRolesIntro()
        {
            ApiResult<List<Rolesintro>> result = new ApiResult<List<Rolesintro>>
            {
                Success = false,
                Message = "未查询到数据"
            };

            var data = await _rolesServer.QueryListAsync(x=>x.Status==1);

            if (data != null){
                result.Success = true;
                result.Message = "查询成功";
                result.Data = _mapper.Map<List<Roles>, List<Rolesintro>>(data);
            }
            return new JsonResult(result);
        }

        /// <summary>
        /// 返回带有层级的菜单信息
        /// 用于 给某角色分配菜单
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetAllMenuTreeListAsync/{roleId:int}")]
        public async Task<JsonResult> GetAllMenuTreeListAsync(int roleId)
        {
            //查询树结构的数据--用作展示菜单，让某一个角色来选择分配
            var tup = await _rolesServer.GetAllMenuTreeListAsync(roleId);

            var result = new JsonResult(new ApiResult<object> ()
            {
                Data = new
                {
                    MenuList = _mapper.Map<List<MenuDTO>>(tup.Item1),
                    OValue = tup.Item2
                },
                Message = "获取树形结构",
                Success = true
            });
            return await Task.FromResult(result);
        }


        /// <summary>
        /// 【设置角色菜单】
        /// </summary>
        /// <param name="setRoleMenu"></param>
        /// <returns></returns>
        [HttpPut]
        [Route("SetRoleMenusAsync")]
        public async Task<JsonResult> SetRoleMenusAsync(SetRoleMenu setRoleMenu)
        {
            ApiResult apiResult = _rolesServer.SetRoleMenus(setRoleMenu.RoleId, setRoleMenu.MenuIds);
            JsonResult result = new JsonResult(apiResult);
            return await Task.FromResult(result);
        }
    }
}
